/**买单
 * Created by huotaol on 2017/10/12.
 */
import React from "react";
import {Button, Form, Input, InputNumber, message, Select} from "antd";
import request, {get} from "@/axios/tools";

const FormItem = Form.Item;
const Option = Select.Option;
const {Search} = Input;
class PayBill extends React.Component {

    static propTypes = {
        data: React.PropTypes.object,
        success: React.PropTypes.func,
    };

    static defaultProps = {
        data: {},
    };

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loading: false,
            itemData: {},
            memberNum: '',
            discountPrice: 0,

        };
    }

    requestTimer = null;

    componentDidMount() {
        // To disabled submit button at the beginning.
        // this.props.form.validateFields();
        this.resetFields();
    }

    componentDidUpdate() {

    }

    resetFields = () => {
        this.props.form.resetFields();
    }
    // 完成订单
    handleSubmit = (e) => {
        const {data, memberInfo} = this.props;
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let user = localStorage.getItem('user');
                let cost = this.state.discountPrice;
                let {id: memberID = 0} = memberInfo;
                let userID;
                if (user) {
                    let {user: userInfo} = JSON.parse(user);
                    if (userInfo) userID = userInfo.id;
                }
                if (values.memberPhone) {
                    delete values.memberPhone;
                }
                this.setState({loading: true});
                const postParam = {
                    ...values,
                    id: this.props.data.id,
                    userID,
                    cost,
                    memberID,
                    change: values.change || 0
                };
                console.log('Received values of form: ', postParam);
                request({url: '/order/item', method: 'put', params: postParam}).then(data => {
                    this.setState({loading: false});
                    this.props.success();
                }).catch(e => {
                    this.setState({loading: false});
                    message.warn('提交失败');
                });
            }
        });
    };

    // 更改折扣
    handleDiscount = (value) => {
        const {data, form} = this.props;
        setTimeout(() => {
            let income = form.getFieldValue('income');
            this.getTotalPrice()
                .then((discountPrice) => {
                    let error
                    // console.log(income, discountCost)
                    if (income !== undefined) {
                        if (income > discountPrice) {
                            form.setFields({'income': {value: income, error}})
                        } else {
                            form.validateFields(['income'])
                        }
                    }
                    this.handleIncomeChange(income);
                })
        }, 0)
    }

    // 获取折扣价格
    getTotalPrice = () => {
        const {form, data} = this.props;
        const billDisCount = parseFloat(form.getFieldValue('discount'));
        return new Promise((resolve, reject) => {
            get('/order/calculateOrder', {id: data.id, discount: billDisCount})
                .then((res) => {
                    // console.log(res)
                    this.setState({
                        discountPrice: res.discountCost
                    }, () => {
                        resolve(res.discountCost);
                    })
                }, (err) => {
                    reject(err)
                })
        })
        // console.log(cost)
    }

    handleIncome = (value) => {
        this.getTotalPrice()
            .then((discountCost) => {
                // this.handleIncomeChange(value)
            });
    }

    // 自动计算找零
    handleIncomeChange = (value) => {
        const {form, data: {cost}} = this.props;
        setTimeout(() => {
            value = value || form.getFieldValue('income');
            let error = form.getFieldError('income');
            if (!error && value !== undefined) {
                let newCost = this.state.discountPrice || cost;
                // console.log(this.state.discountPrice, cost);
                let change = Math.round((value * 1000 - newCost * 1000)) / 1000;
                if (change >= 0) {
                    form.setFieldsValue({change});
                }
            } else {
                form.setFieldsValue({change: ''});
            }
        }, 0)
    }

    // 搜索会员信息
    handleSearchMember = (value) => {
        let {memberNum} = this.state;
        memberNum = memberNum || value;
        if (memberNum) {
            get('/restaurant/member/' + memberNum)
                .then((res) => {
                    this.props.updateMember({...res})
                }, (err) => {
                    console.log(err)
                })
        }
    }

    getPrice = () => {
        return this.state.discountPrice || this.props.data.cost;
    }

    render() {
        const {data, form, memberInfo} = this.props;
        const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched, setFieldsValue} = this.props.form;
        const inputStyle = {width: '100%'};
        const labelStyle = {fontSize: 22};
        const billDisCount = parseFloat(form.getFieldValue('discount'));
        const textHighLight = billDisCount && billDisCount !== 100;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 16},
        };
        const payTypes = [{name: '现金', value: 'CASH'}, {name: '微信支付', value: 'WX_PAY'}, {
            name: '支付宝',
            value: 'ALI_PAY'
        }, {
            name: '美团',
            value: 'MEI_TUAN'
        }, {name: '饿了么', value: 'E_LE_ME'}, {name: '百度', value: 'BAIDU'}];
        return (
            <div className="content-container" style={{marginTop: 0}}>
                <div className="payBill-info">
                    <h2 className="title">{data.tableOrRoom}</h2>
                    <label style={labelStyle}>
                        <span className={'price-label ' + (textHighLight ? '' : 'red-text')}>
                            总价(￥)：
                        </span>
                        <span className={ textHighLight ? '' : 'red-text'}>{data.cost}</span>
                    </label>
                    {
                        textHighLight ? (
                            <label style={labelStyle}>
                                <span className="price-label red-text">
                                    折后价(￥)：
                                </span>
                                <span className="red-text">{this.state.discountPrice}</span>
                            </label>
                        ) : ''
                    }


                </div>
                {/*<Input addonAfter={<span><Icon type="search" /> 搜索</span>} />*/}
                <div className="member-form">
                    <Form >
                        <FormItem
                            label={'折扣（%）'}
                            {...formItemLayout}
                        >
                            {getFieldDecorator('discount', {
                                rules: [{required: true}],
                                initialValue: 100,
                            })(
                                <InputNumber onChange={this.handleDiscount} step={10} min={1} max={100}
                                             style={inputStyle}/>
                            )}
                        </FormItem>
                        <FormItem
                            label={'支付方式'}
                            {...formItemLayout}
                        >
                            {getFieldDecorator('payType', {
                                initialValue: (data.payType && data.payType.key) || '',
                            })(
                                <Select allowClear={true}>
                                    {payTypes.map(v => <Option key={v.value} value={v.value}>{v.name}</Option>)}
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            label={'收入（¥）'}
                            {...formItemLayout}
                        >
                            {getFieldDecorator('income', {
                                rules: [{
                                    required: true, validator: (rule, value, callback) => {
                                        // value >= this.getPrice()
                                        if (true) {
                                            callback();
                                            return;
                                        }
                                        callback('收入应大于账单');
                                    }
                                }],
                                initialValue: data.income,
                            })(
                                <InputNumber onChange={() => this.handleIncome()} style={inputStyle}/>
                            )}
                        </FormItem>
                        <FormItem
                            label={'找零（¥）'}
                            {...formItemLayout}
                        >
                            {getFieldDecorator('change', {
                                rules: [{
                                    required: true,
                                    type: Number,
                                    validator: (rule, value, callback) => {
                                        if (Number(value) >= 0) {
                                            callback();
                                            return;
                                        }
                                        console.log(value)
                                        if (value === '' || typeof value === 'undefined') {
                                            callback();
                                            return;
                                        }
                                        callback('应大于0');
                                    }
                                }],
                                initialValue: data.change
                            })(
                                <InputNumber style={inputStyle}/>
                            )}
                        </FormItem>
                        <FormItem
                            label={'会员'}
                            {...formItemLayout}
                        >
                            {getFieldDecorator('memberPhone')(
                                <Search
                                    placeholder="输入手机号码搜索"
                                    onSearch={value => this.handleSearchMember(value)}
                                />
                            )}
                        </FormItem>
                        {
                            JSON.stringify(memberInfo) !== '{}' ? (
                                <FormItem
                                    label={'会员信息'}
                                    {...formItemLayout}
                                >
                                    <div className="member-info-wrapper">
                                        <div className="info-item">
                                            姓名: <span className="info-text">{memberInfo.name}</span>
                                        </div>
                                        <div className="info-item">
                                            电话: <span className="info-text">{memberInfo.phone}</span>
                                        </div>
                                        <div className="info-item">
                                            消费次数: <span className="info-text">{memberInfo.costCount}</span>
                                        </div>
                                        <div className="info-item">
                                            消费总金额: <span className="info-text">{memberInfo.costTotal}</span>
                                        </div>
                                        <div className="clear-btn">
                                            <Button type="dashed"
                                                    onClick={() => this.props.updateMember({})}>清除</Button>
                                        </div>
                                    </div>
                                </FormItem>
                            ) : ''
                        }
                        <FormItem
                            wrapperCol={{span: 12, offset: 6}}>
                            <Button
                                type="primary"
                                htmlType="submit"
                                onClick={this.handleSubmit}
                                loading={this.state.loading}
                            >
                                提交
                            </Button>
                        </FormItem>
                    </Form>
                </div>
                {/*<div>
                 <div className="member-info">
                 <span className="label-text"></span>


                 </div>
                 <div className="member-info">

                 </div>
                 </div>*/}
            </div>
        );
    }

}


export default Form.create()(PayBill);
